import Vue from 'vue';
const isServer = Vue.prototype.$isServer;


/* istanbul ignore next */
export const on = (function() {
    if (!isServer && document.addEventListener) {
      return function(element, event, handler) {
        if (element && event && handler) {
          element.addEventListener(event, handler, false);
        }
      };
    } else {
      return function(element, event, handler) {
        if (element && event && handler) {
          element.attachEvent('on' + event, handler);
        }
      };
    }
  })();
  
  /* istanbul ignore next */
  export const off = (function() {
    if (!isServer && document.removeEventListener) {
      return function(element, event, handler) {
        if (element && event) {
          element.removeEventListener(event, handler, false);
        }
      };
    } else {
      return function(element, event, handler) {
        if (element && event) {
          element.detachEvent('on' + event, handler);
        }
      };
    }
  })();


  export function rafThrottle(fn) {
    let locked = false;
    return function(...args) {
      if (locked) return;
      locked = true;
      window.requestAnimationFrame(_ => {
        fn.apply(this, args);
        locked = false;
      });
    };
  }


  /* istanbul ignore next */
export function addClass(el, cls) {
    if (!el) return;
    var curClass = el.className;
    var classes = (cls || '').split(' ');
  
    for (var i = 0, j = classes.length; i < j; i++) {
      var clsName = classes[i];
      if (!clsName) continue;
  
      if (el.classList) {
        el.classList.add(clsName);
      } else if (!hasClass(el, clsName)) {
        curClass += ' ' + clsName;
      }
    }
    if (!el.classList) {
      el.setAttribute('class', curClass);
    }
  };
  
  /* istanbul ignore next */
  export function removeClass(el, cls) {
    if (!el || !cls) return;
    var classes = cls.split(' ');
    var curClass = ' ' + el.className + ' ';
  
    for (var i = 0, j = classes.length; i < j; i++) {
      var clsName = classes[i];
      if (!clsName) continue;
  
      if (el.classList) {
        el.classList.remove(clsName);
      } else if (hasClass(el, clsName)) {
        curClass = curClass.replace(' ' + clsName + ' ', ' ');
      }
    }
    if (!el.classList) {
      el.setAttribute('class', trim(curClass));
    }
  };


  export const isFirefox = function() {
    return !Vue.prototype.$isServer && !!window.navigator.userAgent.match(/firefox/i);
  };